package com.aaa.mbs.service.impl;

import com.aaa.common.constants.BusinessConstant;
import com.aaa.mbs.dao.MemberDao;
import com.aaa.mbs.entity.Member;
import com.aaa.mbs.service.MemberService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * (Member)表服务实现类
 *
 * @author makejava
 * @since 2021-01-21 16:05:39
 */
@Service("memberService")
public class MemberServiceImpl implements MemberService {
    @Resource
    private MemberDao memberDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Member queryById(Integer id) {
        return this.memberDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Member> queryAllByLimit(int offset, int limit) {
        return this.memberDao.queryAllByLimit(offset, limit);
    }

    @Override
    public Member getUserByUserName(String userName) {
        Member member=new Member();
        member.setUsername(userName);
        member.setStatus(0);
        List<Member> members = memberDao.queryAll(member);
        if(CollectionUtils.isEmpty(members)){
            return members.get(0);
        }
        return null;
    }

    /**
     * 新增数据
     *  手机端注册方法
     * @param member 实例对象
     * @return 实例对象
     */
    @Override
    public Member insert(Member member) {
        //实例化加密类
        Sha512Hash sha512Hash=new Sha512Hash();
        //设置hash次数
        sha512Hash.setIterations(BusinessConstant.CredentialsPassword.HASH_ITERATIONS);
        //随机盐值
        String salt= UUID.randomUUID().toString().substring(0,15);
        //设置盐值
        sha512Hash.setSalt(ByteSource.Util.bytes(salt));
        //保存盐值
        member.setPwSalt(salt);
        //保存密码
        member.setPassword(sha512Hash.toString());
        this.memberDao.insert(member);
        return member;
    }

    /**
     * 修改数据
     *
     * @param member 实例对象
     * @return 实例对象
     */
    @Override
    public Member update(Member member) {
        this.memberDao.update(member);
        return this.queryById(member.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.memberDao.deleteById(id) > 0;
    }

    /**
     * 通过实体作为筛选条件分页查询
     *
     * @param member 实例对象
     * @return 对象列表
     */
    @Override
    public PageInfo queryAll(int pageNo, int pageSize, Member member) {
        PageHelper.startPage(pageNo, pageSize);
        return new PageInfo<Member>(this.memberDao.queryAll(member));
    }
}